package com.ys.util.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.bo.dto.NameValueSelectDto;
import com.bo.util.StringUtil;
import com.ys.config.MenuId;
import com.ys.dto.RowClickGridConfigDto;
import com.ys.entity.sys.YsCol;
import com.ys.entity.sys.YsDict;
import com.ys.entity.sys.YsMenu;
import com.ys.enume.sys.ConditionEnum;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.sys.CommonService.GridDto;
import com.ys.service.sys.CommonService.GridDto.ColGridDto;
import com.ys.util.DateUtil;
import com.ys.util.shiro.ShiroUtils;

public class GridUtil {
	
	/*
	 * 获取bootstrap table的columns
	 */
	public static List<GridDto.ColGridDto> listColumn(List<YsCol> listYsCol,
			YsMenu ysMenu,
			Map<String, List<YsDict>> KEY_LISTDICT_MAP
			) throws Exception {
		List<GridDto.ColGridDto> colGridArr = new ArrayList<GridDto.ColGridDto>();
		
		// 选中框
		{
			String title = null;
			String field = null;
			String type = "checkbox";
			String totalRowText = null;
			boolean totalRow = false;
			String fixed = "left";
			boolean unresize = true;
			String width = "40";
			String align = null;
			boolean sort = false;
			String templet = null;
			
			colGridArr.add(new GridDto.ColGridDto(title, field, type, totalRowText, totalRow, fixed, unresize, width, align, sort, templet));
		}
		
		{
			String title = "序号";
			String field = null;
			String type = "numbers";
			String totalRowText = null;
			boolean totalRow = false;
			String fixed = "left";
			boolean unresize = true;
			String width = "50";
			String align = "center";
			boolean sort = false;
			String templet = null;
			
			colGridArr.add(new GridDto.ColGridDto(title, field, type, totalRowText, totalRow, fixed, unresize, width, align, sort, templet));
		}
		
		for (YsCol ysCol : listYsCol) {
			if (ysCol.getFrontShow() == YsColEnum.FrontShow.HIDDEN.value) {
				continue;
			}
			
			// TODO 针对库存管理特殊处理
			if (ysCol.getMenuId().longValue() == MenuId.TCC_StockControl.longValue()
					&& "purchasePrice".equals(ysCol.getCode())
					) {
				
				// 9、13、14、18、24、28、31、41、43、48、49、50、51、70
				List<Long> listRoleId = new ArrayList<Long>();
				listRoleId.add(9L);
				listRoleId.add(13L);
				listRoleId.add(14L);
				listRoleId.add(18L);
				listRoleId.add(24L);
				listRoleId.add(28L);
				listRoleId.add(31L);
				listRoleId.add(41L);
				listRoleId.add(43L);
				listRoleId.add(48L);
				listRoleId.add(49L);
				listRoleId.add(50L);
				listRoleId.add(51L);
				listRoleId.add(70L);
				Long loginRoleId = ShiroUtils.getRoleId();
				if (listRoleId.contains(loginRoleId)) {
					continue;
				}
			}
			
			String title = ysCol.getName();
			String field = StringUtil.firstCharacterToLower(ysCol.getCode());
			String type = null;
			String totalRowText = null;
			boolean totalRow = false;
			String fixed = YsColEnum.FrontFixed.getLayerFiexd(ysCol.getFrontFixed());
			boolean unresize = false;
			String width = "" + ysCol.getFrontWidth();
			String align = YsColEnum.FrontAlign.getLayerAlign(ysCol.getFrontAlign());
			boolean sort = true;
			String templet = null;
			
			if (ysCol.getFrontEdit() == YsColEnum.FrontEdit.YES.value) {

				if (YsColEnum.FrontType.TEXT.value.equals(ysCol.getFrontType())) {
					templet = "function(d){return `<input type=\"text\" class=\"layui-input ys-input-table\" name=\"" + ysCol.getCode() + "\" value=\"` + (d." + ysCol.getCode() + " ? d." + ysCol.getCode() + " : ``) + `\" lay-skin=\"input\" lay-filter=\"_input_filter_text_on_table\" lay-event=\"_event_text_change_on_table\">`;}";
				} else if (YsColEnum.FrontType.SELECTOR_DROPDOWN.value.equals(ysCol.getFrontType())) {
					
					if(ysCol.getDictKeyBase() == null || ysCol.getDictKeyBase().length() == 0) {
						templet = "function(d){layer.msg('" + ysCol.getCode() + "尚未设置字典')}";
					} else {
						templet = "function(d){"
								+ "return `<select name=\"" + ysCol.getCode() + "\" lay-filter=\"_input_filter_selector_on_table\">";
						for (YsDict ysDict : KEY_LISTDICT_MAP.get(ysCol.getDictKeyBase())) {
							templet += "<option value=\"" + ysDict.getDictValue() + "\" ` + (d." + ysCol.getCode() + " == '" + ysDict.getDictValue() + "' ? `selected` : ``) + `>" + ysDict.getDictName() + "</option>";
						}
						templet += "</select>`;"
								+ "}";
					}
				} else if (YsColEnum.FrontType.SELECTOR_SWITCH.value.equals(ysCol.getFrontType())) {
					
					if(ysCol.getDictKeyBase() == null || ysCol.getDictKeyBase().length() == 0) {
						templet = "function(d){layer.msg('" + ysCol.getCode() + "尚未设置字典')}";
					} else {
						String layText = "";
						for (YsDict ysDict : KEY_LISTDICT_MAP.get(ysCol.getDictKeyBase())) {
							layText += ysDict.getDictName() + "|";
						}
						layText = layText.substring(0, layText.length() - 1);
						templet = "function(d){"
								+ "return `<input type=\"checkbox\" name=\"" + ysCol.getCode() + "\" value=\"` + d." + ysCol.getCode() + " + `\" lay-skin=\"switch\" lay-text=\"" + layText + "\" lay-filter=\"_input_filter_checkbox_on_table\" ` + (d." + ysCol.getCode() + " == '1' ? `checked` : ``) + `>`"
								+ "}";
					}
				}
			} else {

				if (YsColEnum.FrontType.SELECTOR_DROPDOWN.value.equals(ysCol.getFrontType())) {
					
					if(ysCol.getDictKeyBase() == null || ysCol.getDictKeyBase().length() == 0) {
						templet = "function(d){layer.msg('" + ysCol.getCode() + "尚未设置字典')}";
					} else {
						templet = "function(d){ var options = MAP_DICT['" + ysCol.getDictKeyBase() + "']; "
								+ "for(var i=0;i<options.length;i++){"
									+ "var option = options[i];"
									+ "if(option.value == d." + ysCol.getCode() + "){"
										+ "return option.name;"
									+ "}"
								+ "}"
								+ "return ``;"
								+ "}";
					}
				} else if (YsColEnum.FrontType.SELECTOR_SWITCH.value.equals(ysCol.getFrontType())) {
					
					if(ysCol.getDictKeyBase() == null || ysCol.getDictKeyBase().length() == 0) {
						templet = "function(d){layer.msg('" + ysCol.getCode() + "尚未设置字典')}";
					} else {
						templet = "function(d){ var options = MAP_DICT['" + ysCol.getDictKeyBase() + "']; "
								+ "for(var i=0;i<options.length;i++){"
									+ "var option = options[i];"
									+ "if(option.value == d." + ysCol.getCode() + "){"
										+ "return option.name;"
									+ "}"
								+ "}"
								+ "return ``;"
								+ "}";
					}
				} else if (YsColEnum.FrontType.IMG.value.equals(ysCol.getFrontType())) {//图片
					templet = "function(d){"
							+ "if(!d." + ysCol.getCode() + ") {return ``;}"
							+ "return `<img src=\"` + d." + ysCol.getCode() + " + `\" style=\"max-height:30px; max-width: 30px;\"  onclick=\"layer.photos({photos: {'title': '图片预览','start': 0,'data': [{'src': '` +  d." + ysCol.getCode() + " + ` '}]},closeBtn: 1});\" />`;"
							+ "}";
				} else if (YsColEnum.FrontType.FILE_MULTY.value.equals(ysCol.getFrontType())) {//附件（多）

					templet = "function(d){"
							+ "if(!d." + ysCol.getCode() + ") {return ``;}"
							+"return `<input id=\"id_multy_file_" + System.currentTimeMillis() + "\" class=\"layui-input\" style=\"text-align: "+YsColEnum.FrontAlign.getLayerAlign(ysCol.getFrontAlign())+";cursor: pointer;color: #4DB6FD;\" code=\"" + ysCol.getCode() + "\"  data-filter=\"_input_filter_file_multy_on_table_in_form\" data-source-code=\"" + ysCol.getCode() + "\" data-source-type=\"" + ysCol.getMultyFileSourceType() + "\" data-source-id=\"`+d.sourceId+`\" value=\"`+d." + ysCol.getCode() + "+`\" readonly=\"readonly\" />`;"
							+ "}";



				} else if (YsColEnum.FrontType.SELF_DEFINE_TPL.value.equals(ysCol.getFrontType())) {
					templet = "#" + getTempletId(ysCol);
				} else if (YsColEnum.FrontType.FILE.value.equals(ysCol.getFrontType())) {//附件

					templet = "function(d){"
							+ "if(!d." + ysCol.getCode() + ") {return ``;}"
							+"return `<i title=\"点击下载\" class=\"layui-icon layui-icon-file\" style=\"text-align: "+YsColEnum.FrontAlign.getLayerAlign(ysCol.getFrontAlign())+";cursor: pointer;color: #4DB6FD;font-size: 20px;font-weight:bold;\" data-url=\"`+d." + ysCol.getCode() + "+`\" data-filter=\"_input_filter_file_on_table_in_form\"  ></i> `;"
							+ "}";
				} else if (YsColEnum.FrontType.HYPER_LINK.value.equals(ysCol.getFrontType())) {//超链接

					templet = "function(d){"
							+ "if(!d." + ysCol.getCode() + ") {return ``;}"
							+"return `<a style=\"text-decoration: underline;cursor: pointer;color: #4DB6FD;\" onclick=\"window.open(\'`+d." + ysCol.getCode() + "+`\');\" >`+d." + ysCol.getCode() + "+`</a> `;"
							+ "}";
				}
			}
			colGridArr.add(new GridDto.ColGridDto(title, field, type, totalRowText, totalRow, fixed, unresize, width, align, sort, templet));
		}
		return colGridArr;
	}
	
	/*
	 * 获取搜索的输入框
	 */
	public static List<GridDto.ConditionDto> listCondition(List<YsCol> listYsCol, Map<String, String> initCondCodeValue) {
		List<GridDto.ConditionDto> listCondition = new ArrayList<GridDto.ConditionDto>();
		for (YsCol ysCol : listYsCol) {
			if (initCondCodeValue.containsKey(ysCol.getCode())) {
				ysCol.setFrontConditionDefault(initCondCodeValue.get(ysCol.getCode()));
			}
			GridDto.ConditionDto conditionDto = getCondition(ysCol);
			if (conditionDto != null) {
				listCondition.add(conditionDto);
			}
		}
		
		return listCondition;
	}
	
	/*
	 * 获取搜索的输入框
	 */
	public static GridDto.ConditionDto getCondition(YsCol ysCol) {
		
		if (YsColEnum.FrontConditionState.NO.value == ysCol.getFrontConditionState()) {
			return null;
		}
		
		Long id = ysCol.getId();
		String name = ysCol.getName();
		String code = ysCol.getFrontConditionCode() != null && ysCol.getFrontConditionCode().length() > 0 ? ysCol.getFrontConditionCode() : ysCol.getCode();
		String type = ysCol.getFrontConditionType();
		String rangeType = ysCol.getFrontConditionRangeType();
		String value = ysCol.getFrontConditionDefault();
		
		if (value != null && value.length() > 0) {
			if (value.equals(ConditionEnum.DefaultValue.LATEST_TWO_DAY.value)) {
				Date now = new Date();
				value = DateUtil.getYYYY_MM_DD(DateUtil.addDays(now, -1)) + " ~ " + DateUtil.getYYYY_MM_DD(now);
			} else if (value.equals(ConditionEnum.DefaultValue.LATEST_TWO_DATETIME.value)) {
				Date now = new Date();
				value = DateUtil.getYYYY_MM_DD(DateUtil.addDays(now, -1)) + " 00:00:00 ~ " + DateUtil.getYYYY_MM_DD(now) + " 23:59:59";
			} else if (value.equals(ConditionEnum.DefaultValue.CURRENT_YEAR.value)) {
				value = DateUtil.getYYYY(new Date());
			}else if (value.equals(ConditionEnum.DefaultValue.CURRENT_MONTH.value)) {
				value = DateUtil.getYYYY_MM(new Date())+ " ~ " + DateUtil.getYYYY_MM(new Date());
			}
		}
		String placeHolder = YsColEnum.FrontConditionRangeType.getName(ysCol.getFrontConditionRangeType());
		
		if (YsColEnum.FrontConditionType.TEXT.value.equals(type)) {
			return new GridDto.ConditionDto(id, code, type, rangeType, name, value, placeHolder, null);
		} else if (YsColEnum.FrontConditionType.DATE_YYMMDD.value.equals(type)) {
			return new GridDto.ConditionDto(id, code, type, rangeType, name, value, placeHolder, null);
		} else if (YsColEnum.FrontConditionType.DATE_YYMM.value.equals(type)) {
			return new GridDto.ConditionDto(id, code, type, rangeType, name, value, placeHolder, null);
		} else if (YsColEnum.FrontConditionType.DATE_YY.value.equals(type)) {
			return new GridDto.ConditionDto(id, code, type, rangeType, name, value, placeHolder, null);
		} else if (YsColEnum.FrontConditionType.DATE_YYMMDDHHMMSS.value.equals(type)) {
			return new GridDto.ConditionDto(id, code, type, rangeType, name, value, placeHolder, null);
		} else if (YsColEnum.FrontConditionType.SELECTOR_MODAL_SINGLE.value.equals(type)) {
			return new GridDto.ConditionDto(id, code, type, rangeType, name, value, placeHolder, null);
		}
		else if (YsColEnum.FrontConditionType.SELECTOR_DROPDOWN.value.equals(type)
				|| YsColEnum.FrontConditionType.SELECTOR_SWITCH.value.equals(type)) {
			List<NameValueSelectDto> optionArr = new ArrayList<NameValueSelectDto>();
			optionArr.add(new NameValueSelectDto("请选择", "", true));
			List<YsDict> listDict = new YsDict().setDictKey(ysCol.getDictKeyBase()).setOrderby("A.SortNo asc").queryList();
			for(YsDict ysDict : listDict) {
				String name2 = ysDict.getDictName();
				String value2 = ysDict.getDictValue();
				boolean isSelected = false;
				optionArr.add(new NameValueSelectDto(name2, value2, isSelected));
			}
			return new GridDto.ConditionDto(id, code, type, rangeType, name, value, placeHolder, optionArr);
		}
		else {
			return null;
		}
	}
	
	
	/*
	 * 获取字段的引用节点-选择框(转换)
	 * <script type="text/html" id="switchTpl">
	 * <input type="checkbox" name="xxxxx" value="{{d.xxxxx}}" lay-skin="switch" lay-text="女|男" lay-filter="input_filter_xx" {{ d.xxxxx == 1 ? 'checked' : '' }}>
	 * </script>
	 */
	private static String TEMPLET_SCRIPT_SWITCH = "<input type=\"checkbox\" name=\"RP_CODE\" value=\"{{d.RP_CODE}}\" lay-skin=\"switch\" lay-text=\"RP_NAME_ARR\" lay-filter=\"_input_filter_checkbox_on_table\" {{ d.RP_CODE == 'RP_FIRST_VALUE' ? 'checked' : '' }} RP_DISABLED>";
	private static String TEMPLET_SCRIPT_TEXT = "<input type=\"text\" class=\"layui-input ys-input-table\" name=\"RP_CODE\" value=\"{{d.RP_CODE}}\" lay-skin=\"input\" lay-filter=\"_input_filter_text_on_table\" lay-event=\"_event_text_change_on_table\" RP_DISABLED>";
	private static String TEMPLET_SCRIPT_IMG = "{{# if(d.RP_CODE){ }}<img src=\"{{d.RP_CODE}}\" style=\"max-height:30px; max-width: 30px;\"/>{{# }else{ }}{{# } }}";
	public static String getDomScriptHtml(YsCol ysCol, List<YsDict> listYsDictThis) {
		String field = StringUtil.firstCharacterToLower(ysCol.getCode());
		if (YsColEnum.FrontType.SELECTOR_SWITCH.value.equals(ysCol.getFrontType())) {

			// 字典名称字符串，格式：A|B
			String dictNames = listYsDictThis.get(0).getDictName() + "|" + listYsDictThis.get(1).getDictName();
			
			String templetScript = TEMPLET_SCRIPT_SWITCH
					.replace("RP_CODE", field)
					.replace("RP_NAME_ARR", dictNames)
					.replace("RP_FIRST_VALUE", listYsDictThis.get(0).getDictValue())
					.replace("RP_DISABLED", ysCol.getFrontEdit() == YsColEnum.FrontEdit.YES.value ? "" : "disabled");
			return templetScript;
		} else if (YsColEnum.FrontType.SELECTOR_DROPDOWN.value.equals(ysCol.getFrontType())) {
			
			String templetScript = "<select name=\"" + field + "\" lay-filter=\"_input_filter_selector_on_table\" " + (ysCol.getFrontEdit() == YsColEnum.FrontEdit.YES.value ? "" : "disabled") + ">";
			for(YsDict tbBaseInfo : listYsDictThis) {
				templetScript += "{{#  if(d." + field + " == '" + tbBaseInfo.getDictValue() + "'){ }} <option value=\"" + tbBaseInfo.getDictValue() + "\" selected>" + tbBaseInfo.getDictName() + "</option>"
						+ "{{#  } else { }} <option value=\"" + tbBaseInfo.getDictValue() + "\">" + tbBaseInfo.getDictName() + "</option>"
						+ "{{#  } }}";
			}
			templetScript += "</select>";
			return templetScript;
		} else if (YsColEnum.FrontType.TEXT.value.equals(ysCol.getFrontType())) {
			if (ysCol.getFrontEdit() == YsColEnum.FrontEdit.YES.value) {
				String templetScript = TEMPLET_SCRIPT_TEXT
						.replace("RP_CODE", field)
						.replace("RP_DISABLED", "");
				return templetScript;
			} else {
				return null;
			}
		} else if (YsColEnum.FrontType.IMG.value.equals(ysCol.getFrontType())) {
			String templetScript = TEMPLET_SCRIPT_IMG
					.replace("RP_CODE", field);
			return templetScript;
		} else {
			return null;
		}
	}
	
	/*
	 * 获取templet的命名
	 * 格式：templet_script_xxxx
	 */
	public static String getTempletId(YsCol ysCol) {
		
		return "templet_script_" + ysCol.getId();
	}
	
	/*
	 * 获取表单lay-filter的命名
	 * 格式：input_filter_xxxx
	 */
	public static String getFilterNameInput(YsCol ysCol) {
		
		return "input_filter_" + ysCol.getCode();
	}
	
	/*
	 * 获取选择框lay-filter的命名
	 * 格式：select_filter_xxxx
	 */
	public static String getFilterNameSelector(YsCol ysCol) {
		
		return "select_filter_" + ysCol.getCode();
	}
	
	public static String ColGridToString(List<GridDto.ColGridDto> colGridArr) {
		StringBuffer sb = new StringBuffer("[");
		for (int i = 0; colGridArr != null && i < colGridArr.size(); i++) {
			ColGridDto colGridDto = colGridArr.get(i);
			
			if (i == 0) {
				sb.append(colGridDto.toString());
			} else {
				sb.append("," + colGridDto.toString());
			}
		}
		sb.append("]");
		return sb.toString();
	}


	public static String RowClickGridConfigDtoToString(List<RowClickGridConfigDto.ColDto> colGridArr) {
		StringBuffer sb = new StringBuffer("[");
		for (int i = 0; colGridArr != null && i < colGridArr.size(); i++) {
			RowClickGridConfigDto.ColDto colDto = colGridArr.get(i);

			if (i == 0) {
				sb.append(colDto.toString());
			} else {
				sb.append("," + colDto.toString());
			}
		}
		sb.append("]");
		return sb.toString();
	}
	
	public static void main(String[] args) {
		System.out.println(TEMPLET_SCRIPT_SWITCH.replace("RP_CODE", "aaaaaa"));
	}
}
